#! /usr/bin/env bash

# Run regular maintenance jobs in host's crontab after 'sf up' has been started
# PHY: crontab -l | grep -v cronjob | echo "15 0 * * sun /sf/sfbin/cronjob all >/dev/shm/sf/run/logs/cronjob.out" | crontab -


SF_MV_EXIT_FN="/sf/data/share/relay-exit-nodes-mullvad.txt"
SF_MV_RELAY_FN="/sf/data/share/proxies.txt"
SF_TOR_EXIT_FN="/sf/data/share/tor-exit-nodes.txt"
# SF_GLOBAL_EXIT_FN="/sf/config/etc/relay-exit-nodes-global.txt" # Provided by Blind Mouse
# aka curl -H "Auth: hAV2fDFN..." http://92.x.x.x:50613 >/sf/config/etc/relay-exit-nodes-global.txt

# Make a list of working proxies
# and exit mullvad proxy IPs.
mk_mullvad_relays()
{
    local IFS
    local str
    local arr
    local ip
    local ips
    local proxies

    docker exec sf-mullvad true 2>/dev/null || { echo >&2 "sf-mullvad not running. Execute this after ${CDC}sfbin/sf${CN} up"; return; }

    IFS=""
    str=$(curl -fsSL --retry 3 --max-time 15 https://api.mullvad.net/www/relays/all/ 2>/dev/null | jq -r '.[] |  select(.socks_name != null) | select(.socks_port != null)  | "\(.socks_name):\(.socks_port)"' |grep -v ^-)
    str=${str//[^a-z0-9-:.$'\n']}
    [[ -z $str ]] && return

    IFS=$'\n'
    arr=($str)
    for h in "${arr[@]}"; do
        echo -n "Testing $h - "
        ip=$(docker exec sf-mullvad bash -c "curl --retry 1 --max-time 5 -fsSL -x 'socks5://$h'  ipinfo.io" | jq -r '.ip | select(. != null)')
        ip=${ip//[^a-f0-9:.]}
        [[ -z $ip ]] && { echo "SKIP"; continue; }
        echo "$ip"
        ips+="$ip"$'\n'
        proxies+="$h"$'\n'
    done
    echo -n "$proxies" >"${SF_MV_RELAY_FN}"
    echo -n "$ips" >"${SF_MV_EXIT_FN}"
}

mk_tor_relays()
{
    local IFS
    local str
    IFS=""
    str=$(curl -SsfL --retry 3 --max-time 15 'https://www.dan.me.uk/torlist/?exit')
    [[ -z $str ]] && return
    echo -n "$str" >"${SF_TOR_EXIT_FN}"
}

mk_global_relays()
{
    local IFS
    local str

    echo "NOT YET IMPLEMENTED. We are using a private list from Blind Mouse"
    # IFS=""
    # str=${str//[^a-z0-9-.$'\n']}
    # [[ -z $str ]] && return

    # echo "$str" >"${SF_GLOBAL_EXIT_FN}"
}

str="$*"
[[ $str == *all* ]] && str="mullvad tor global"

[[ $str == *mullvad* ]] && { mk_mullvad_relays; is_ran=1; }
[[ $str == *tor* ]] && { mk_tor_relays; is_ran=1; }
# [[ $str == *global* ]] && { mk_global_relays; is_ran=1; }

[[ -n $is_ran ]] && exit

echo "Usage: $0 [mullvad, tor, all]"